<?php

declare(strict_types=1);

namespace app\admin\controller\v1;

use app\common\Backend;
use app\common\model\Invoice;
use app\common\model\PublicStatus;
use think\Request;

class InvoiceCon extends Backend
{
    /**
     * @var Navigation
     */
    protected $model = null;

    protected $quickSearchField = ['title'];

    protected $withJoinTable = ['order', 'user'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new Invoice();
    }

    /**
     * 数据源
     * @throws Throwable
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }
        $limit = $this->request->param('limit', 10);
        $res = $this->model
            ->with(['order' => function ($query) {
                $query->withField(['id', 'remark', 'order_no']);
                return $query;
            }, 'user' => function ($q) {
                $q->withField(['id', 'username']);
                return $q;
            }])
            ->paginate($limit)->each(function ($item, $key) {
                $item['invoice_type_text'] = PublicStatus::$invoiceType[$item['invoice_type']];
                $item['invoice_header_type_text'] = PublicStatus::$invoiceHeaderType[$item['invoice_header_type']];
                $item['invoice_service_text'] = PublicStatus::$invoiceService[$item['invoice_service']];
                return $item;
            });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => '',
        ]);
    }


    //查看详情
    public function invoiveDetail(): void
    {
        $id = $this->request->param('id');
        $res = $this->model
            ->with(['order' => function ($query) {
                $query->withField(['id', 'remark', 'order_no']);
                return $query;
            }, 'user' => function ($q) {
                $q->withField(['id', 'username']);
                return $q;
            }])
            ->find($id);
        $res['invoice_type_text'] = PublicStatus::$invoiceType[$res['invoice_type']]?? '其他';
        $res['invoice_header_type_text'] = PublicStatus::$invoiceHeaderType[$res['invoice_header_type']]?? '其他';
        $res['invoice_service_text'] = PublicStatus::$invoiceService[$res['invoice_service']] ?? '其他';

        $this->success('', [
            'list'   => $res
        ]);
    }


    //发送到邮箱
    public function invoiveSendEmail() : void {
        $id = $this->request->param('id');
        $res = $this->model->findOrEmpty($id);
        if ($res->isEmpty()) {
            $this->error('未找到数据');
        }
        $res->invoice_status = PublicStatus::PUBLIC_STATUS_ONE;
        $res->order->invoice_status = PublicStatus::PUBLIC_STATUS_ONE;
        $res->together(['order'])->save();
        $this->success('OK');
    }
}
